// 模块依赖
const path = require('path');
const Koa = require('koa');
const next = require('next');
const serve = require('koa-static');
const Router = require('koa-router');
const mount = require('koa-mount');

//全局配置
const config = require('./config');
global.__API_CONFIG__ = config;
 
// 环境
const port = parseInt(process.env.PORT, 10) || 5008;
const dev = process.env.NODE_ENV !== 'production';

//实例化
const app = next({ dev });

//路由
const routes = require('./routes');
const handle = routes.getRequestHandler(app);

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();

  server.use(
    mount(
      '/static',
      serve(path.join(__dirname, '../static'), {
        maxAge: 36500,
      }),
    ),
  );

  router.get('*', async ctx => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
  });

  server.use(async (ctx, next) => {
    ctx.res.statusCode = 200;
    await next();
  });

  server.use(router.routes());

  server.on('error', (err, ctx) => {
    console.error('server error', err);
  })

  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`, new Date());
  });
});